package com.anteater.eattheant.view;

import java.util.ArrayList;
import java.util.List;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;

public class Maze extends Group {

	public static final float HEIGHT = 1.0f;
	public static final float WIDTH = 2.0f;

	private final float scaleFactor;
	private final short graph[][];
	private final List<Escape> escapes;

	public Maze(short graph[][],
			List<com.anteater.eattheant.util.Escape> escapes, GL10 gl,
			Context context) {
		super();

		this.graph = graph;
		scaleFactor = HEIGHT / (Tunnel.HEIGHT * graph.length);

		for (short i = 0; i < graph.length; i++) {
			for (short j = 0; j < graph[i].length; j++) {
				if (graph[i][j] > 0) {
					add(new Tunnel(i, j, graph[i][j], gl, context));
				}
			}
		}

		this.escapes = new ArrayList<Escape>(escapes.size());
		for (com.anteater.eattheant.util.Escape escape : escapes) {
			this.escapes.add(new Escape(escape.getI(), escape.getJ(), gl, context));
		}
	}

	@Override
	public void draw(GL10 gl) {
		class Drawer {
			float h = Tunnel.HEIGHT * scaleFactor;
			float w = Tunnel.WIDTH * scaleFactor;

			void draw(GL10 gl, short i, short j, Mesh mesh) {
				gl.glPushMatrix();

				float ux = (float) (-WIDTH / 2.0f + j * w);
				float uy = (float) (HEIGHT / 2.0f - i * h);
				float x = ux + w / 2.0f;
				float y = uy - h / 2.0f;

				gl.glTranslatef(x, y, 0);
				gl.glScalef(scaleFactor, scaleFactor, scaleFactor);

				mesh.draw(gl);

				gl.glPopMatrix();
			}
		}

		Drawer dr = new Drawer();

		for (int i = 0; i < size(); i++) {
			dr.draw(gl, ((Tunnel) get(i)).getI(), ((Tunnel) get(i)).getJ(),
					get(i));
		}
		for (Escape escape : escapes) {
			dr.draw(gl, escape.getI(), escape.getJ(), escape);
		}
	}

	public float getScaleFactor() {
		return scaleFactor;
	}

	public short[][] getGraph() {
		return graph;
	}

	public List<Escape> getEscapes() {
		return escapes;
	}
}
